package org.performancetracker;

/**
 * @author: jaronschut
 */

public class FactoryHelper<T> { 
	private static final String LOG_ERROR_CLASS = "Could not find class name: ";
	private static final String LOG_ERROR_INSTANTIATION = "Could not instantiate class: ";
	private static final String LOG_ERROR_ACCESS = "Could not access class: ";

	T instantiate(Class defaultClass, String property) {

		String className = System.getProperty(property);
		Class factoryClass = null;

		if (className == null || className == "") {

			try {
				return (T) defaultClass.newInstance();

			}  catch (InstantiationException e) {

				throw new IllegalArgumentException(LOG_ERROR_INSTANTIATION + factoryClass, e);

			} catch (IllegalAccessException e) {

				throw new IllegalArgumentException(LOG_ERROR_ACCESS + factoryClass, e);
			}

		} else {

			try {
				factoryClass = Class.forName(className);
				return (T) factoryClass.newInstance();

			} catch (ClassNotFoundException e) {

				throw new IllegalArgumentException(LOG_ERROR_CLASS + className, e);

			} catch (InstantiationException e) {

				throw new IllegalArgumentException(LOG_ERROR_INSTANTIATION + factoryClass, e);

			} catch (IllegalAccessException e) {

				throw new IllegalArgumentException(LOG_ERROR_ACCESS + factoryClass, e);
			}
		}
	}

}
